/*
 * @Description: 串口通信相关自定义接口
 * @Date: 2024-02-02 15:05:44
 * @FilePath: \demod:\12electron\electron-demo\src\main\serialport.ts
 */
import { BrowserWindow } from 'electron';
import { SerialPort } from 'serialport';

let serialPortConnection: any = null; // 串口连接

// 获取串口列表
const getSerialPortList: any = async () => {
  const list = await SerialPort.list();
  console.log(list);
  return list;
};

// 创建串口连接
const creatSerialPortConnection: any = async (portName: string) => {
  console.log('创建串口连接-串口名：' + portName);
  serialPortConnection = new SerialPort({
    path: portName,
    baudRate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    autoOpen: false,
  });
  return new Promise((resolve, reject) => {
    serialPortConnection.open((err) => {
      if (err) {
        console.log('---创建串口连接失败: ' + err.message + '\n');
        serialPortConnection.close(); // 关闭连接
        reject(err);
      }

      serialPortConnection.on('error', (err) => {
        console.log('1发生错误: ' + err.message + '\n');
      });

      serialPortConnection.on('data', (data) => {
        const hexData = [...data].map((byte) => byte.toString(16).padStart(2, '0')).join(' ');
        console.log('Received Hex Data:', hexData);
        console.log('2收到数据: ' + data + '\n');
        // 将接收到的数据发送到渲染进程
        const win = BrowserWindow.getAllWindows()[0];
        const webContents = win.webContents;
        webContents.send('serialport:sendData:reply', data.toString());
      });
      console.log('---串口连接成功' + '\n');
      resolve(portName);
    });
  });
};

// 向指定端口发送数据
const sendSerialPortData = async (portName: string, data: string) => {
  console.log('串口名：' + portName);
  console.log('发送数据：' + data);

  try {
    serialPortConnection.write(data);
  } catch (err: any) {
    console.log('3发送数据失败: ' + err.message + '\n');
  }
};

export { creatSerialPortConnection, getSerialPortList, sendSerialPortData };
